//
//  TestHealthkitViewController.m
//  BluetoothDemo
//
//  Created by RJ on 2020/12/14.
//  Copyright © 2020 RJ. All rights reserved.
//

#import "TestHealthkitViewController.h"
#import <HealthKit/HealthKit.h>

@interface TestHealthkitViewController ()
@property (weak, nonatomic) IBOutlet UITextView *infoTextView;
@property (weak, nonatomic) IBOutlet UIButton *reloadButton;

@property (strong, nonatomic) HKHealthStore *healthStore;

@end

@implementation TestHealthkitViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.healthStore = [[HKHealthStore alloc] init];
    // Do any additional setup after loading the view.
}

/**
 检查HealthKit权限
 */
- (void)checkAvailableWithCallback: (void(^)(BOOL))callback{
    if([HKHealthStore isHealthDataAvailable]){
        HKObjectType *bmiType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMassIndex]; // BMI
        HKObjectType *heightType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeight]; // 身高
        HKObjectType *bodyMassType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMass]; // 体重
        HKObjectType *bodyFatRateType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyFatPercentage]; // 体脂率
        HKObjectType *activeEnergyType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned]; // 活动能量
        HKObjectType *workoutType = [HKObjectType workoutType]; // 体能训练
        
        // 要写入的字段
        NSMutableSet * shareType = [NSMutableSet setWithObjects:bmiType, heightType, bodyMassType, bodyFatRateType, activeEnergyType, workoutType, nil];
        // 需要读取的字段
        NSMutableSet * readType = [NSMutableSet setWithObjects:bmiType, heightType, bodyMassType, bodyFatRateType, activeEnergyType, workoutType, nil];
        [self.healthStore requestAuthorizationToShareTypes:shareType readTypes:readType completion:^(BOOL success, NSError * _Nullable error) {
            if(success){
                callback(YES);
            } else {
                callback(NO);
            }
        }];
    } else{
        callback(NO);
    }
}

- (void)saveBodyHeightData: (double)height{
    //写入身高
    NSString *heightIdentifierString = HKQuantityTypeIdentifierHeight;
    HKQuantityType *heightType = [HKObjectType quantityTypeForIdentifier:heightIdentifierString];
    HKQuantity *heightQuantity = [HKQuantity quantityWithUnit:[HKUnit meterUnit] doubleValue:height];
    HKQuantitySample *heightSample = [HKQuantitySample quantitySampleWithType:heightType quantity:heightQuantity startDate:[NSDate date] endDate:[NSDate date]];
    [self.healthStore saveObject:heightSample withCompletion:^(BOOL success, NSError * _Nullable error) {
        if(success){
            NSLog(@"写入身高成功");
        } else {
            NSLog(@"%@", error);
        }
    }];
}

- (void)saveBodyMassData: (double)bodyMass{
    //写入体重
    NSString *bodyMassIdentifierString = HKQuantityTypeIdentifierBodyMass;
    HKQuantityType *bodyMassType = [HKObjectType quantityTypeForIdentifier:bodyMassIdentifierString];
    HKQuantity *bodyMassQuantity = [HKQuantity quantityWithUnit:[HKUnit gramUnit] doubleValue: bodyMass]; // 70kg
    HKQuantitySample *bodyMassSample = [HKQuantitySample quantitySampleWithType:bodyMassType quantity:bodyMassQuantity startDate:[NSDate date] endDate:[NSDate date]];
    [self.healthStore saveObject:bodyMassSample withCompletion:^(BOOL success, NSError * _Nullable error) {
        if(success){
            NSLog(@"写入体重成功");
        } else {
            NSLog(@"%@", error);
        }
    }];
}

- (void)saveBodyFatRateData: (double)bodyFatRate{
    // 写入体脂率
    NSString *fatRateIdentifierString = HKQuantityTypeIdentifierBodyFatPercentage;
    HKQuantityType *fatRateType = [HKObjectType quantityTypeForIdentifier:fatRateIdentifierString];
    HKQuantity *fatRateQuantity = [HKQuantity quantityWithUnit:[HKUnit percentUnit] doubleValue:bodyFatRate];
    HKQuantitySample *fatRateSample = [HKQuantitySample quantitySampleWithType:fatRateType quantity:fatRateQuantity startDate:[NSDate date] endDate:[NSDate date]];
    [self.healthStore saveObject:fatRateSample withCompletion:^(BOOL success, NSError * _Nullable error) {
        if(success){
            NSLog(@"写入体脂率成功");
        } else {
            NSLog(@"%@", error);
        }
    }];
}

- (void)saveBMIData: (double)bmi{
    // 写入bmi指数
    NSString *bmiIdentifierString = HKQuantityTypeIdentifierBodyMassIndex; // BMI指数
    HKQuantityType *bmiType = [HKObjectType quantityTypeForIdentifier:bmiIdentifierString];
    HKQuantity *bmiQuantity = [HKQuantity quantityWithUnit:[HKUnit countUnit] doubleValue:23];
    HKQuantitySample *bmiSample = [HKQuantitySample quantitySampleWithType:bmiType quantity:bmiQuantity startDate:[NSDate date] endDate:[NSDate date]];
    
    [self.healthStore saveObject:bmiSample withCompletion:^(BOOL success, NSError * _Nullable error) {
        if(success){
            NSLog(@"写入bmi数据成功");
        }else {
            NSLog(@"%@", error);
        }
    }];
}

- (void)saveActiveEnergyData: (double)activeEnergy{
    // 写入活动能量消耗数据
    NSString *activeEnergyIdentifier = HKQuantityTypeIdentifierActiveEnergyBurned;
    HKQuantityType * activeEenrgyType = [HKObjectType quantityTypeForIdentifier:activeEnergyIdentifier];
    HKQuantity * myEnergy = [HKQuantity quantityWithUnit:[HKUnit kilocalorieUnit] doubleValue:activeEnergy];
    NSDate *date = [NSDate date];
    HKQuantitySample *energySample = [HKQuantitySample quantitySampleWithType:activeEenrgyType quantity:myEnergy startDate:date endDate:[NSDate dateWithTimeInterval:60 * 5 sinceDate:date]];
    [self.healthStore saveObject:energySample withCompletion:^(BOOL success, NSError * _Nullable error) {
        if(success){
            NSLog(@"写入活动能量数据成功");
        }else {
            NSLog(@"%@", error);
        }
    }];
}

- (void)saveWorkOutData{
    // 写入体能训练数据
    HKQuantity *energyBurned = [HKQuantity quantityWithUnit:[HKUnit kilocalorieUnit] doubleValue:400];
    HKQuantity *distance = [HKQuantity quantityWithUnit:[HKUnit mileUnit] doubleValue:3.2];
    
    HKWorkout *run = [HKWorkout workoutWithActivityType:HKWorkoutActivityTypeRunning
                                                  startDate:[NSDate date]
                                                    endDate:[NSDate dateWithTimeIntervalSinceNow:60 * 30]
                                                   duration:60 * 30
                                          totalEnergyBurned:energyBurned
                                              totalDistance:distance
                                                   metadata:nil];
    [self.healthStore saveObject:run withCompletion:^(BOOL success, NSError * _Nullable error) {
        if(success){
            NSLog(@"写入体能训练数据成功");
        } else {
            NSLog(@"%@", error);
        }
    }];
}

- (IBAction)reloadAction:(id)sender {
    [self checkAvailableWithCallback:^(BOOL available) {
        if(available){
            // 写入身高
            [self saveBodyHeightData:1.78];
            
            // 写入体重
            [self saveBodyMassData:70 * 1000];
            
            // 写入体脂率
            [self saveBodyFatRateData:0.3];
            
            // 写入bmi指数
            [self saveBMIData:22];
            
            // 写入活动能量消耗数据
            [self saveActiveEnergyData:123];

            // 写入体能训练数据
            [self saveWorkOutData];
        }
    }];
}

@end
